package com.sunnada.edu.business.contract.service;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.sunnada.edu.business.contract.dao.ContractDao;
import com.sunnada.edu.business.project.service.ProjectMethods;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.pub.util.Utils;

@Service
@Transactional
public class ContractServiceImpl implements ContractService {
	private static final Logger logger = LoggerFactory
			.getLogger(ContractServiceImpl.class);
	@Resource
	ContractDao contractDao;

	@Override
	public int getContractCots(HashMap<String, String> params) {
		return contractDao.getContractCots(params);
	}

	@Override
	public List<?> findContracts(HashMap<String, String> params) {
		return contractDao.findContracts(params);
	}

	@Override
	public String contractDelete(HashMap<String, String> params) {
		String msg = "";
		int num = contractDao.contractDelete(params);
		ContractMethods.deleteWorkerContract(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String contractAdd(HttpServletRequest request,
			HashMap<String, String> params) {
		String msg = "";
		String recId = UUID.randomUUID().toString();
		params.put("recId", recId);
		int num = contractDao.contractAdd(params);
		if (num == 0) {
			msg = "0";// 失败
		} else {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				List<MultipartFile> filelist = multiRequest
						.getFiles("contract");// 图片列表
				for (int i = 0; i < filelist.size(); i++) {
					MultipartFile file = filelist.get(i);
					String fileName = file.getOriginalFilename();// 原文件名
					String fileType = file.getContentType();// 原文件类型
					String name = file.getName();// form表单字段name属性值
					// 存文件
					String savePath = FileSave(file, request);
					params.put("path", savePath);
					params.put("fileName", fileName);
					params.put("owner", recId);
					ProjectMethods.contractAdd(params);// 添加工程合同
				}

			}
			msg = "1";// 成功

		}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String contractUpdate(HttpServletRequest request,
			HashMap<String, String> params) {
		String msg = "";
		int num = ContractMethods.updateWorkerContract(params);
		if (num == 0) {
			msg = "0";// 失败
		} else {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				List<MultipartFile> filelist = multiRequest
						.getFiles("contract");// 图片列表
				for (int i = 0; i < filelist.size(); i++) {
					MultipartFile file = filelist.get(i);
					String fileName = file.getOriginalFilename();// 原文件名
					String fileType = file.getContentType();// 原文件类型
					String name = file.getName();// form表单字段name属性值
					// 存文件
					String savePath = FileSave(file, request);
					params.put("path", savePath);
					params.put("fileName", fileName);
					params.put("owner", params.get("recId"));
					ProjectMethods.contractAdd(params);// 添加工程合同
				}

			}
			msg = "1";// 成功
		}

		return msg;
	}

	@Override
	public Map getContractByRecId(HashMap<String, String> params) {
		return contractDao.getContractByRecId(params);
	}

	@Override
	public Map<String, String> getContract(HashMap<String, String> params) {
		return contractDao.getContract(params);
	}

	@Override
	public String contractEnable(HashMap<String, String> params) {
		String msg = "";
		int num = contractDao.contractEnable(params);
		if (num == 0) {
			msg = "启用失败！";
		}
		return msg;
	}

	@Override
	public String contractDisable(HashMap<String, String> params) {
		String msg = "";
		int num = contractDao.contractDisable(params);
		if (num == 0) {
			msg = "停用失败！";
		}
		return msg;
	}

	public String FileSave(MultipartFile file, HttpServletRequest request) {
		if (Utils.isNull(file)) {
			return "";
		}
		// 实际名称
		String fileName = file.getOriginalFilename();
		// 保存附件
		if (Utils.isNotNull(fileName)) {
			// 物理根目录
			String rootPath = request.getSession().getServletContext()
					.getRealPath("/");
			// 相对路径
			String filePath = "upload/contract/"
					+ DateUtil.simpleDateFormat("yyyyMM").format(new Date());
			// 保存文件路径
			String savePath = filePath
					+ "/"
					+ DateUtil.simpleDateFormat("yyyyMMddHHmmssSSS").format(
							new Date())
					+ fileName.substring(fileName.lastIndexOf("."),
							fileName.length());

			if (!new File(rootPath + filePath).exists()) {
				new File(rootPath + filePath).mkdirs();
			}

			try {
				file.transferTo(new File(rootPath + savePath));
				return savePath;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return "";
	}

}
